<template>
	<view class="content">
		<view class="tishi">请绑定邮箱，以保证帐号正常使用</view>
		<view class="inputbkc">
			<input v-model.trim="email" class="email" focus placeholder="邮箱地址" v-model="email"/>
		</view>
		<view>
			<button class="btn" type="default" @click="saveemail">确定</button>			
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				email: '',
				uid: ''
			}
		},
		onLoad(option) {
			this.email = option.email;
			this.uid = option.uid;
		},
		methods: {
			saveemail() {
				// 设置信箱
				if(this.email.trim() == '') {
					// 提示不能输入空信箱
					uni.showToast({
					    title: '请输入邮箱地址',
						icon: 'none',
					    duration: 2000
					});
					return;
				}
				// 判断邮箱地址格式
				var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
				if(!reg.test(this.email.trim())) {
					uni.showToast({
					    title: '邮箱地址格式错误',
						icon: 'none',
					    duration: 2000
					});
					return;
				}
				uni.request({
				    url: 'https://www.yedushu.cn/api/saveemail',  // 保存信箱
				    data: {
				        email: this.email,
						uid: this.uid
				    },
					method: 'POST',
				    success: (res) => {
						console.log(JSON.stringify(res));
						if(res.data.code == 1){
							var userinfo = uni.getStorageSync('userinfo');
							// console.log(JSON.stringify(userinfo));
							userinfo['email'] = this.email; // 设置对象中的值
							uni.setStorageSync('userinfo', userinfo);  // 重新存储到本地
							// console.log(JSON.stringify(userinfo));
							// 触发资料与帐号设置（setmyselft.vue）页上的事件，更新用户信箱
							uni.$emit("setemail",{
									email: this.email,
								},
							);
							// 信箱修改成功，返回上一页
							uni.navigateBack({
							    delta: 1
							});
						}
						if(res.data.code == 2){
							uni.showToast({
							    title: '信箱已被注册过',
								icon: 'none',
							    duration: 2000
							});
							return;
						}
				    }
				});
			},
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		padding: 10px 10px;
	}
	.tishi {
		padding: 5px 7px;
		color: #b2b2b2;
		font-size: 14px;
	}
	.inputbkc {
		margin: 10px 7px;
		border: 1px solid #b2b2b2;
		padding: 7px 7px;
		border-radius: 7px;
	}
	.btn {
		background-color: #00cc33;
		color: #FFFFFF;
	}
</style>
